from PySide2.QtCore import QObject,QIODevice,Signal
from PySide2.QtSerialPort import QSerialPort
class MyTp(QObject):
    def __init__(self):
        QObject.__init__(self) 
        self.begin=False;
        self.isOpen=False;
        self.pmyport=None;
        self.old_value=-99999;
        self.str_list=[]
        self.last=""
    dataArrive=Signal(float)
    def open(self):
        self.pmyport=QSerialPort();
        self.pmyport.setPortName("/dev/pts/1");
        self.pmyport.setBaudRate(QSerialPort.Baud1200);
        self.pmyport.setDataBits(QSerialPort.Data7);
        self.pmyport.setParity(QSerialPort.OddParity);
        self.pmyport.setStopBits(QSerialPort.OneStop);
        self.pmyport.setFlowControl(QSerialPort.NoFlowControl);
        if (self.pmyport.open(QIODevice.ReadWrite)):
            print("open")
            self.isOpen=True;
            self.pmyport.readyRead.connect(self.onReady)
        else:
            print("open error")
            print(self.pmyport.error())
            self.isOpen=False;
    def parse(self,str0):
        # print(str0)
        str0=bytes(str0)
        str1=""
        str1+=self.last
        str1+=str0.decode("utf-8")
        list1 = str1.split("\r")
        # print(list1)
        if(self.begin):
            for i in range(len(list1)-1):#(i = 0; i < list1.size()-1; ++i):
                self.str_list.append(list1[i]);
            self.last=list1[len(list1)-1];
        else:
            if (len(list1)>1):
                self.begin=True    
                for i in range(len(list1)-1): # (i = 1; i < list1.size()-1; ++i):
                    self.str_list.append(list1[i]);
                self.last=list1[len(list1)-1]
        l=self.read();
        # print(l)
        self.dataArrive.emit(l);
    def onReady(self):
        # print("onReady")
        data = self.pmyport.readAll();
        self.parse(data)
    def read(self):
        if(len(self.str_list)<1):
            return self.old_value
        msg=self.str_list[len(self.str_list)-1];
        msg=msg[2:12];
        return float(msg)
if __name__ == "__main__":
    from PySide2 import QtCore
    from mytp import MyTp
    import sys
    a=QtCore.QCoreApplication()
    tp1=MyTp()
    tp1.open()
    sys.exit(a.exec_())    
